package cn.kgc.filter;

import cn.kgc.common.vo.Result;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {

    /**
     * 过滤器类型
     * 过滤的时机
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 优先级，数字越小优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否要执行该过滤器
     * @return
     */
    @Override
    public boolean shouldFilter() {

        return true;
    }

    /**
     * 过滤的逻辑
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
//        System.out.println("-------");
//        获取请求token
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
//        判断token是否有效
        if (token == null){
//         未登录,返回json结果
            ctx.setSendZuulResponse(false);
//            ctx.setResponseStatusCode(401);   //401-未授权
            ctx.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);   //401-未授权
            HttpServletResponse response = ctx.getResponse();
            response.setContentType("application/json;charset=utf-8");
            Result<Object> result = Result.fail(20001, "无效认证，请重新登录");
            try {
                response.getWriter().write(JSON.toJSONString(result));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
//        有效，则放行
        return null;
    }
}
